package com.xwj.controller.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import com.xwj.Enums.StatusInfoEnum;
import com.xwj.data.StaticData;
import com.xwj.dto.OrderInfoDto;
import com.xwj.entity.OrderDetailEntity;
import com.xwj.entity.RaOrder;
import com.xwj.rabbitmq.Producter.AddOrderSender;
import com.xwj.service.Impl.RaHouseInfoServiceImpl;
import com.xwj.service.Impl.RaOrderServiceImpl;
import com.xwj.service.Impl.RaStatusInfoServiceImpl;
import com.xwj.service.holder.RaRegisterUserHolder;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/front/myCenter/myOrder/")
public class FrontOrderController {

    @Autowired
    private RaOrderServiceImpl raOrderService;
    @Autowired
    private AddOrderSender addOrderSender;
    @Autowired
    private RaStatusInfoServiceImpl raStatusInfoService;
    @Autowired
    private RaHouseInfoServiceImpl raHouseInfoService;

    @RequestMapping(value = "myOrderList", method = RequestMethod.GET)
    public ModelAndView myOrderList(ModelAndView modelAndView) {
        String label = StatusInfoEnum.OrderInfo.getName();
        modelAndView.addObject("orderStatus", raStatusInfoService.findStatusByLabel(label));
        modelAndView.setViewName("/front/order/myOrder");
        return modelAndView;
    }

    @RequestMapping(value = "myPublishOrderList", method = RequestMethod.GET)
    public ModelAndView myPublishOrderList(ModelAndView modelAndView) {
        String label = StatusInfoEnum.OrderInfo.getName();
        modelAndView.addObject("orderStatus", raStatusInfoService.findStatusByLabel(label));
        modelAndView.setViewName("/front/order/myPublishOrder");
        return modelAndView;
    }

    /**
     * 我收到的租赁单 显示或查询
     *
     * @param pageIndex
     * @param pageSize
     * @param key
     * @return
     */
    @RequestMapping(value = "myOrderInfoDetail", method = RequestMethod.POST)
    public Map<String, Object> myOrderInfoList(@RequestParam(value = "page") Integer pageIndex,
                                               @RequestParam(value = "limit") Integer pageSize,
                                               @RequestParam(value = "key", required = false) String key,
                                               HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String userId = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        PageInfo<RaOrder> page;
        OrderInfoDto orderInfoDto = null;
        if (key != null) orderInfoDto = JSON.parseObject(key, new TypeReference<OrderInfoDto>() {
        });
        if (orderInfoDto == null)
            page = raOrderService.findOrderByTenantIdWithPage(pageIndex, pageSize, userId);
        else {
            orderInfoDto.setTenantId(userId);
            page = raOrderService.frontFindByPropertyWithPage(pageIndex, pageSize, orderInfoDto);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getTotal());
        map.put("data", page.getList());
        return map;
    }

    /**
     * 我发的租赁单 显示或查询
     *
     * @param pageIndex
     * @param pageSize
     * @param key
     * @return
     */
    @RequestMapping(value = "myPushOrderInfoList", method = RequestMethod.POST)
    public Map<String, Object> myPushOrderInfoList(@RequestParam(value = "page") Integer pageIndex,
                                                   @RequestParam(value = "limit") Integer pageSize,
                                                   @RequestParam(value = "key", required = false) String key,
                                                   HttpServletRequest request) {
        ServletContext context = request.getServletContext();
        String userId = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        PageInfo<RaOrder> page;
        OrderInfoDto orderInfoDto = null;
        if (key != null) orderInfoDto = JSON.parseObject(key, new TypeReference<OrderInfoDto>() {
        });
        if (orderInfoDto == null)
            page = raOrderService.findOrderByLandlordIdWithPage(pageIndex, pageSize, userId);
        else {
            orderInfoDto.setLandlordId(userId);
            page = raOrderService.frontFindByPropertyWithPage(pageIndex, pageSize, orderInfoDto);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getTotal());
        map.put("data", page.getList());
        return map;
    }


    /**
     * 给租户发送租赁单
     *
     * @param raOrder
     * @return
     */
    @RequestMapping(value = "pushOneOrder", method = RequestMethod.POST)
    public Map<String, Object> pushOneOrder(RaOrder raOrder, OrderDetailEntity orderDetailEntity, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        ServletContext context = request.getServletContext();
        String userId = (String) context.getAttribute(StaticData.REGISTER_USER_LOGIN_ATTRIBUTE);
        List<String> houseIdList = raOrderService.findOrderByLandlordId(userId).stream().filter(r -> r.getStatus() <= 2).map(RaOrder::getHourseId).collect(Collectors.toList());
        if (houseIdList.contains(raOrder.getHourseId())) {
            map.put("msg", "该房子已发单，不能再重复发，请与先前的单解除联系再发新单");
            return map;
        }
        raOrder.setLandlordId(userId);
        if (StringUtils.isNotBlank(raOrder.getTenantId()) && !RaRegisterUserHolder.hasUser(raOrder.getTenantId())) {
            map.put("msg", "无此用户:" + raOrder.getTenantId());
            return map;
        }
        if (orderDetailEntity.getLongRent().equals(StaticData.LONG_TIME_STR) && orderDetailEntity.getLease() < StaticData.LONG_TIME_RENT_LEASE) {
            map.put("msg", "长租期限必须多于等于" + StaticData.LONG_TIME_RENT_LEASE + "个月");
            return map;
        }
        String expireTime = DateTime.parse(orderDetailEntity.getEffectTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
                .plusMonths(orderDetailEntity.getLease()).toString("yyyy-MM-dd HH:mm:ss");
        orderDetailEntity.setExpireTime(expireTime);
        String detail = JSON.toJSONString(orderDetailEntity);
        raOrder.setDetailInfo(detail);
        addOrderSender.send(JSON.toJSONString(raOrder)); //放到消息队列里处理
        map.put("msg", "添加成功");
        return map;
    }

    /**
     * 未确认的订单可以修改详情
     *
     * @param id
     * @param orderDetailEntity
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @RequestMapping(value = "updateDetail", method = RequestMethod.POST)
    public Map<String, Object> updateDetail(String id, OrderDetailEntity orderDetailEntity) throws ExecutionException, InterruptedException {
        Map<String, Object> map = new HashMap<>();
        if (orderDetailEntity.getLongRent().equals(StaticData.LONG_TIME_STR) && orderDetailEntity.getLease() < StaticData.LONG_TIME_RENT_LEASE) {
            map.put("msg", "长租期限必须多于等于" + StaticData.LONG_TIME_RENT_LEASE + "个月");
            return map;
        }
        String expireTime = DateTime.parse(orderDetailEntity.getEffectTime(), DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
                .plusDays(orderDetailEntity.getLease()).toString("yyyy-MM-dd HH:mm:ss");
        orderDetailEntity.setExpireTime(expireTime);
        if (raOrderService.updateDetailSync(id, orderDetailEntity).get())
            map.put("msg", "订单详情更新成功");
        else
            map.put("msg", "订单详情更新失败");
        return map;
    }

    /**
     * 用户更改订单状态
     *
     * @param orderInfoDto
     * @return
     */
    @RequestMapping(value = "updateOrderStatus", method = RequestMethod.POST)
    public Map<String, Object> updateOrderStatus(OrderInfoDto orderInfoDto) {
        Map<String, Object> map = new HashMap<>();
        if (raOrderService.updateProperty(orderInfoDto) > 0) {
            if (orderInfoDto.getStatus() == 1) { //租客确认订单后房屋改为已出租状态
                Map<String, Object> value = new HashMap<>();
                value.put("id", raOrderService.findOrderById(orderInfoDto.getId()).getHourseId());
                value.put("status", orderInfoDto.getStatus());
                raHouseInfoService.updateStatus(value);
            }
            map.put("msg", "状态更新成功");
        } else
            map.put("msg", "状态更新失败");
        return map;
    }

    /**
     * 删除（更改del_flag的值，用户看不到而已，后台仍然可以看到数据）
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "deleteById", method = RequestMethod.POST)
    public Map<String, Object> deleteById(@RequestParam("id") String id) throws ExecutionException, InterruptedException {
        List<String> ids = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        ids.add(id);
        if (raOrderService.updateDelflag(ids).get())
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

    /**
     * 批量删除
     *
     * @param mydata
     * @return
     */
    @RequestMapping(value = "deleteBatchById", method = RequestMethod.POST)
    public Map<String, Object> deleteBatchById(@RequestParam(value = "mydata", required = false) String mydata) throws ExecutionException, InterruptedException {
        Map<String, Object> map = new HashMap<>();
        List<RaOrder> raOrderList = JSON.parseArray(mydata, RaOrder.class);
        if (raOrderList.size() == 0) {
            map.put("msg", "未选中任何选项");
            return map;
        }
        List<String> ids = raOrderService.parseListId(raOrderList);
        if (raOrderService.updateDelflag(ids).get())
            map.put("msg", "删除成功");
        else
            map.put("msg", "数据操作异常");
        return map;
    }

}
